package com.go.ssh.point.web.account.action;

import java.util.List;

import com.go.ssh.commons.Constants;
import com.go.ssh.commons.web.action.BaseAction;
import com.go.ssh.point.exception.UserExistsException;
import com.go.ssh.point.exception.UserNotFoundException;
import com.go.ssh.point.model.RoleModel;
import com.go.ssh.point.model.UserModel;
import com.go.ssh.point.service.IAccountService;
import com.go.ssh.point.service.IRoleService;
import com.go.ssh.point.web.account.vo.AccountInfo;

@SuppressWarnings("serial")
public class AccountAction extends BaseAction {
	private IAccountService accountService;
	private IRoleService roleService;
	private AccountInfo accountInfo;
	private List<RoleModel> roles;

	public String doLogin() {
		try {
			UserModel userModel = new UserModel();
			userModel.setUsername(accountInfo.getUsername());
			userModel.setPassword(accountInfo.getPassword());
			userModel = accountService.login(userModel);
			accountInfo.setUsername(userModel.getUsername());
			accountInfo.setPassword(userModel.getPassword());
			accountInfo.setRoles(userModel.getRoles());
			getActionContext().getSession().put(
					Constants.USER_INFO_SESSION_KEY, accountInfo);
		} catch (UserNotFoundException e) {
			return LOGIN;
		}
		return SUCCESS;
	}

	public String doRegister() {
		UserModel user = new UserModel();
		user.setUsername(accountInfo.getUsername());
		user.setPassword(accountInfo.getPassword());

		try {
			accountService.register(user);
		} catch (UserExistsException e) {
			return INPUT;
		}

		return SUCCESS;
	}

	public String register() {
		roles = roleService.listAll();
		return SUCCESS;
	}

	public String logout() {
		getActionContext().getSession().remove(Constants.USER_INFO_SESSION_KEY);
		return SUCCESS;
	}

	public AccountInfo getAccountInfo() {
		return accountInfo;
	}

	public void setAccountInfo(AccountInfo accountVO) {
		this.accountInfo = accountVO;
	}

	public IAccountService getAccountService() {
		return accountService;
	}

	public void setAccountService(IAccountService accountService) {
		this.accountService = accountService;
	}

	public List<RoleModel> getRoles() {
		return roles;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
}
